package com.example.demo.Configurations;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

@Configuration
public class BookShopDataSourceInitializer {
    @Value("classpath:SQL/drop.sql")
    private Resource sqlDrop;
    @Value("classpath:SQL/user.sql")
    private Resource sqlUser;
    @Value("classpath:SQL/book.sql")
    private Resource sqlBook;
    @Value("classpath:SQL/order.sql")
    private Resource sqlOrder;

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator(){
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(sqlDrop);
        populator.addScript(sqlUser);
        populator.addScript(sqlBook);
        populator.addScript(sqlOrder);
        populator.setSeparator("$$$"); // 分隔符，默认为;
        return populator;
    }
}
